package com.photoeditor.demo.model.store.module;

import android.text.TextUtils;

import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import static com.photoeditor.demo.ui.adapter.home.HomeAdapter.TYPE_BASE_ITEM;
import static com.photoeditor.demo.util.FeatureCodeUtil.addFeatureString;

/**
 * Created by mutour on 2017/5/8.
 */

public class StoreOnlineBean implements Serializable, MultiItemEntity {

    private static final long serialVersionUID = 1967042364617231879L;

    public static final String STORE_STORY_PREFIX = "url://";

    public static final String STORE_STORY_OTHER_COUNTRY = "OTHER";

    /**
     * id: 当前bean的id，type为category时，categoryId为0
     */
    private String id;

    /**
     * 名字
     */
    private String name;

    /**
     * 分类id：只有type为item时有效，代表当前id所在分类的id
     */
    private String categoryId;

    /**
     * 展示类型
     */
    private String style;

    /**
     *
     */
    private String param;

    /**
     * 故事内容
     */
    private String story;

    /**
     * 作者
     */
    private String author;

    /**
     * 作者跳转
     */
    private String authorUrl;

    /**
     * 最后更新时间戳
     */
    private String lastUpdate;

    /**
     * 滤镜小图片
     */
    private String icon;

    /**
     * 浏览图，多个图片#分割
     */
    private String preview;

    /**
     * sticker预览图
     */
    private List<String> stickerUrls;

    /**
     * 贴纸集合预览图
     */
    private String tab;

    /**
     * 滤镜banner图，一般用来显示到推荐页面
     */
    private String banner;

    /**
     * 包名
     */
    private String pkgName;

    /**
     * 大小
     */
    private String size;

    /**
     * 下载地址

     */
    private String downurl;

    /**
     * 跳转链接地址， 只有当type == TYPE_ITEM时才有效
     */
    private String jumpUrl;

    private String rootUrl;

    /**
     * 推荐
     */
    private ArrayList<StoreOnlineBean> recommends;

    /**
     * 子模块
     */
    private ArrayList<StoreOnlineBean> childModules;

    /**
     * 是否拍照界面加锁
     */
    private boolean isLockMain;

    /**
     * 是否加锁
     */

    private boolean isBuy;

    /**
     * 加锁位置
     */
    private int lockPosition;
    /**
     * 是否去Google Play下载
     */
    private boolean isDownloadOnGP;

    public static final int TYPE_ROOT = 0;
    public static final int TYPE_FUNC = 1;
    public static final int TYPE_CATEGORY = 2;
    public static final int TYPE_ITEM = 3;
    public static final int TYPE_UNKNOWN = -1;
    public static final int LOCK_PAGE_MAIN = 1;
    public static final int LOCK_PAGE_DETAIL = 2;

    /**
     * 内容类型(分类、item)
     */
    private int type;

    /**
     * 滤镜版本
     */
    private int versioncode;

    /**
     * 支持显示的版本号，此字段如果大于本地配置的可显示版本，该item会在解析的时候被过滤掉
     */
    private int displayVersion;

    /**
     * 点击hot features后的跳转目的地
     */
    private String action;

    /** 下面为本地内置数据使用 start **/
    private boolean isBuildin;
    private int resIconName;
    private String assetName;
    /** 下面为本地内置数据使用 end **/
    private int resourceId;//本地肌肉贴纸资源

    private String count;

    public String getCount() {
        return count;
    }

    public void setCount(String count) {
        this.count = count;
    }

    public void setLockMain(boolean lockMain) {
        isLockMain = lockMain;
    }

    public void setBuy(boolean buy) {
        isBuy = buy;
    }

    public boolean isLockMain() {
        return isLockMain;
    }

    public boolean isBuy() {
        // TODO: 18/4/12 pcp 1.0 不支持非免费资源
//        return false;
        return isBuy;
    }

    public void setAction(String action) {
        this.action = action;
    }

    public String getAction() {
        return action;
    }

    public int getLockPosition() {
        return lockPosition;
    }

    public void setLockPosition(int lockPosition) {
        this.lockPosition = lockPosition;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(String categoryId) {
        this.categoryId = categoryId;
    }

    public String getStyle() {
        return style;
    }

    public void setStyle(String style) {
        this.style = style;
    }

    public String getParam() {
        return param;
    }

    public void setParam(String param) {
        this.param = param;
    }

    public String getStory() {
        return story;
    }

    public void setStory(String story) {
        this.story = story;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getAuthorUrl() {
        return authorUrl;
    }

    public void setAuthorUrl(String authorUrl) {
        this.authorUrl = authorUrl;
    }

    public String getLastUpdate() {
        return lastUpdate;
    }

    public void setLastUpdate(String lastUpdate) {
        this.lastUpdate = lastUpdate;
    }

    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon;
    }

    public String getPreview() {
        return preview;
    }

    public void setPreview(String preview) {
        this.preview = preview;
    }

    public List<String> getStickerUrls() {
        return stickerUrls;
    }

    public void setStickerUrls(List<String> stickerUrls) {
        this.stickerUrls = stickerUrls;
    }

    public String getBanner() {
        return banner;
    }

    public void setBanner(String banner) {
        this.banner = banner;
    }

    public String getTab() {
        return tab;
    }

    public void setTab(String tab) {
        this.tab = tab;
    }

    public String getPkgName() {
        return pkgName;
    }

    public void setPkgName(String pkgName) {
        this.pkgName = pkgName;
    }

    public String getSize() {
        return size;
    }

    public void setSize(String size) {
        this.size = size;
    }

    public String getDownUrl() {
        return downurl;
    }

    public void setDownurl(String downurl) {
        this.downurl = downurl;
    }

    public String getJumpUrl() {
        return jumpUrl;
    }

    public void setJumpUrl(String jumpUrl) {
        this.jumpUrl = jumpUrl;
    }

    public String getRootUrl() {
        return rootUrl;
    }

    public void setRootUrl(String rootUrl) {
        this.rootUrl = rootUrl;
    }

    public ArrayList<StoreOnlineBean> getRecommends() {
        return recommends;
    }

    public void setRecommends(ArrayList<StoreOnlineBean> recommends) {
        this.recommends = recommends;
    }

    public ArrayList<StoreOnlineBean> getChildModules() {
        return childModules;
    }

    public void setChildModules(ArrayList<StoreOnlineBean> childModules) {
        this.childModules = childModules;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public void setVersioncode(int versioncode) {
        this.versioncode = versioncode;
    }

    public int getVersioncode() {
        return versioncode;
    }

    public void setDisplayVersion(int displayVersion) {
        this.displayVersion = displayVersion;
    }

    public int getDisplayVersion() {
        return displayVersion;
    }

    public boolean isDownloadOnGP() {
        // TODO: 18/4/12 pcp 1.0 不支持外部apk
        return false;
//        return isDownloadOnGP;
    }

    public void setDownloadOnGP(boolean downloadOnGP) {
        isDownloadOnGP = downloadOnGP;
    }

    public static StoreOnlineBean parse(String jsonStr) {
        return new Gson().fromJson(jsonStr, StoreOnlineBean.class);
    }

    /**
     * 剔除url的query参数
     * @param url
     * @return
     */
    public static String removeQueryString(String url) {
        if (!TextUtils.isEmpty(url)) {
            int queryIndex = url.indexOf("?");
            if (queryIndex != -1) {
                return url.substring(0, url.indexOf("?"));
            }
        }
        return url;
    }

    public static StoreOnlineBean parse(JSONObject json, StoreOnlineBean parent) {
        StoreOnlineBean bean = new StoreOnlineBean();

        String author = parent != null ? parent.getAuthor() : "";
        String authorUrl = parent != null ? parent.getAuthorUrl() : "";
        String lastUpdate = parent != null ? parent.getLastUpdate() : "";
        String categoryId = parent != null ? parent.getId() : "";
        String rootUrl = removeQueryString(parent != null ? parent.getRootUrl() : "");
        bean.setCount(json.optString("count", ""));
        bean.setId(json.optString("id", ""));
        bean.setName(json.optString("name", ""));
        bean.setCategoryId(json.optString("cId", categoryId));
        bean.setStyle(json.optString("style", ""));
        bean.setParam(json.optString("param", ""));
        bean.setAuthor(json.optString("author", author));
        bean.setAuthorUrl(json.optString("aUrl", authorUrl));
        bean.setLastUpdate(json.optString("time", lastUpdate));
        bean.setPkgName(json.optString("pkgname", ""));
        bean.setSize(json.optString("size", ""));
        bean.setType(json.optInt("type", TYPE_UNKNOWN));
        //加锁
        bean.setBuy(json.optBoolean("isBuy", false));
        bean.setLockMain(json.optBoolean("isLockMain", false));
        bean.setLockPosition(json.optInt("lockPos", -1));

        bean.setDownloadOnGP(json.optBoolean("isDownloadOnGP", false));

        // 如果当前节点有rootUrl，则以当前的为准
        String currentRootUrl = json.optString("rootUrl", rootUrl);
        bean.setRootUrl(addFeatureString(currentRootUrl));

        String icon = json.optString("icon", null);
        String preview = json.optString("preview", null);
        String banner = json.optString("banner", null);
        String tab = json.optString("tab", null);
        bean.setIcon(addFeatureString(icon != null ? StoreParseUtil.joinUrl(currentRootUrl, icon) : ""));
        bean.setBanner(addFeatureString(banner != null ? StoreParseUtil.joinUrl(currentRootUrl, banner) : ""));
        bean.setTab(addFeatureString(tab != null ? StoreParseUtil.joinUrl(currentRootUrl, tab) : ""));
        if (preview != null) {
            String[] previews = preview.split("#");
            if (previews.length == 1) {
                preview = addFeatureString(StoreParseUtil.joinUrl(currentRootUrl, preview));
            } else if (previews.length > 1) {
                StringBuilder sb = new StringBuilder();
                for (String pv : previews) {
                    sb.append(addFeatureString(StoreParseUtil.joinUrl(currentRootUrl, pv)));
                    sb.append("#");
                }
                sb.deleteCharAt(sb.length() - 1);
                preview = sb.toString();
            }
            bean.setPreview(preview);
        } else {
            bean.setPreview("");
        }

        String action = json.optString("action", null);
        if (action == null) {
            bean.setAction("");
        } else {
            bean.setAction(action);
        }

        String stickerUrls = json.optString("stickerUrls", null);
        if (stickerUrls != null) {
            List<String> stringList = new ArrayList<>();
            String[] stickerUrlArr = stickerUrls.split("#");
            if (stickerUrlArr.length == 1) {
                stringList.add(addFeatureString(StoreParseUtil.joinUrl(currentRootUrl, stickerUrlArr[0])));
            } else if (stickerUrlArr.length > 1) {
                for (String pv : stickerUrlArr) {
                    stringList.add(addFeatureString(StoreParseUtil.joinUrl(currentRootUrl, pv)));
                }
            }
            bean.setStickerUrls(stringList);
        } else {
            bean.setStickerUrls(null);
        }

        String downurl = json.optString("downurl", null);
        bean.setDownurl(addFeatureString(downurl != null ? StoreParseUtil.joinUrl(currentRootUrl, downurl) : ""));

        bean.setJumpUrl(addFeatureString(json.optString("jumpUrl", "")));

        String story = json.optString("story", null);
        if (story != null) {
            if (story.startsWith(STORE_STORY_PREFIX)) {
                story = STORE_STORY_PREFIX + StoreParseUtil.joinUrl(currentRootUrl, story.substring(STORE_STORY_PREFIX.length()));
            }
            bean.setStory(story);
        } else {
            bean.setStory("");
        }

        ArrayList<String> ids = null;
        JSONArray recommendJsonArr = json.optJSONArray("recommend");
        if (recommendJsonArr != null) {
            ids = new ArrayList<>(recommendJsonArr.length());
            for (int i = 0; i < recommendJsonArr.length(); ++i) {
                String id = recommendJsonArr.optString(i);
                if (TextUtils.isEmpty(id)) {
                    continue;
                }
                ids.add(id);
            }
        }
        if (ids != null) {
            bean.recommends = new ArrayList<>(ids.size());
        }

        bean.setVersioncode(json.optInt("version", TYPE_UNKNOWN));
        bean.setDisplayVersion(json.optInt("displayversion", TYPE_UNKNOWN));

        JSONArray childModulesJsonArr = json.optJSONArray("child");

        if (childModulesJsonArr != null) {
            bean.childModules = new ArrayList<>(childModulesJsonArr.length());
            for (int i = 0; i < childModulesJsonArr.length(); ++i) {
                JSONObject filterJsonObj = childModulesJsonArr.optJSONObject(i);
                if (filterJsonObj == null) {
                    continue;
                }
                StoreOnlineBean filterOnlineBean = StoreOnlineBean.parse(filterJsonObj, bean);
                bean.childModules.add(filterOnlineBean);
                String id = filterOnlineBean.getId();
                if (ids != null && !TextUtils.isEmpty(id) && ids.contains(id)) {
                    bean.recommends.add(filterOnlineBean);
                }
            }
        }

        return bean;
    }

    public String getAssetName() {
        return assetName;
    }

    public void setAssetName(String assetName) {
        this.assetName = assetName;
    }

    public int getResIconName() {
        return resIconName;
    }

    public void setResIconName(int resIconName) {
        this.resIconName = resIconName;
    }

    public boolean isBuildin() {
        return isBuildin;
    }

    public void setBuildin(boolean buildin) {
        isBuildin = buildin;
    }

    /**
     * 肌肉贴纸资源
     * @return
     */
    public int getResourceId() {
        return resourceId;
    }

    /**
     * 肌肉贴纸资源
     * @return
     */
    public void setResourceId(int resourceId) {
        this.resourceId = resourceId;
    }

    public String toJson() {
        return new Gson().toJson(this);
    }

    @Override
    public String toString() {
        return "StoreOnlineBean{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", categoryId='" + categoryId + '\'' +
                ", style='" + style + '\'' +
                ", param='" + param + '\'' +
                ", story='" + story + '\'' +
                ", author='" + author + '\'' +
                ", authorUrl='" + authorUrl + '\'' +
                ", lastUpdate='" + lastUpdate + '\'' +
                ", icon='" + icon + '\'' +
                ", preview='" + preview + '\'' +
                ", stickerUrls=" + stickerUrls +
                ", tab='" + tab + '\'' +
                ", banner='" + banner + '\'' +
                ", pkgName='" + pkgName + '\'' +
                ", size='" + size + '\'' +
                ", downurl='" + downurl + '\'' +
                ", jumpUrl='" + jumpUrl + '\'' +
                ", rootUrl='" + rootUrl + '\'' +
                ", recommends=" + recommends +
                ", childModules=" + childModules +
                ", isLockMain=" + isLockMain +
                ", isBuy=" + isBuy +
                ", lockPosition=" + lockPosition +
                ", isDownloadOnGP=" + isDownloadOnGP +
                ", type=" + type +
                ", versioncode=" + versioncode +
                ", displayVersion=" + displayVersion +
                ", action='" + action + '\'' +
                ", isBuildin=" + isBuildin +
                ", resIconName=" + resIconName +
                ", assetName='" + assetName + '\'' +
                ", resourceId=" + resourceId +
                ", count='" + count + '\'' +
                '}';
    }

    @Override
    public int getItemType() {
        return TYPE_BASE_ITEM;
    }
}